<template>
  <div>
    <el-container>
      <el-header style="height:auto;">
        <!--        <el-select v-model="select_web" placeholder="选择网站" size="small" filterable clearable @change="handleSearch">-->
        <!--          <el-option label="所有" value=""></el-option>-->
        <!--          <el-option v-for="item in websites" :key="item.id" :label="item.domain"-->
        <!--                     :value="item.id"></el-option>-->
        <!--        </el-select>-->
        <single_website_select :website="select_web" :multiple="false" size="small" @change="function(v){select_web=v}" />
        <el-select v-model="select_type" placeholder="过滤类型" size="small" filterable clearable @change="handleSearch">
          <el-option label="所有" value="" />
          <el-option label="注册未支付" value="registe_not_pay" />
          <el-option label="支付成功" value="order_success" />
          <el-option label="只加购物车" value="only_add_cart" />
        </el-select>
        <el-input v-model="kwInput" placeholder="输入产品ID搜索" style="width: 80%" clearable class="" @keyup.native.enter="handleSearch">
          <el-button slot="append" style="width: 180px" type="success" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        </el-input>
        <el-button type="success" @click="googleConversionFileVisual=true">转化文件</el-button>
      </el-header>
      <el-main>
        <el-table
          ref="shopingcarttable"
          v-loading="listLoading"
          :data="data"
          border
          height="750"
          :default-sort="{prop: 'create_at', order: 'descending'}"
          @sort-change="handleSort"
        >
          <el-table-column align="center" prop="id_cart" label="cart" sortable="custom" width="250">
            <template slot-scope="scope">
              {{ scope.row.website__domain }}|{{ scope.row.id_cart }}
            </template>
          </el-table-column>
          <el-table-column align="center" prop="email" label="用户信息" width="200">
            <template slot-scope="scope">
              {{ scope.row.email }}<br>
              {{ scope.row.firstname + ' ' + scope.row.lastname }}
              <el-alert
                v-if="scope.row.promote_email"
                title="该邮箱已经发送过邮件"
                type="warning"
              />
              <el-button v-if="scope.row.promote_email" size="mini" type="danger" @click="handleReplayEmail(scope.row)">发送邮件</el-button>
              <el-button v-else size="mini" type="success" @click="handleReplayEmail(scope.row)">发送邮件</el-button>

            </template>
          </el-table-column>
          <el-table-column align="center" prop="id_product" label="product" width="80">
            <template slot-scope="scope">

              <el-link type="success" :href="scope.row.product_url" :title="scope.row.product_name">{{ scope.row.id_product }}</el-link>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="id_order" label="order" width="120" sortable="custom" />
          <el-table-column align="center" prop="price" label="price" width="80" />
          <el-table-column align="center" prop="quantity" label="quantity" width="90" />
          <el-table-column align="center" prop="ip" label="ip" width="140" />
          <el-table-column align="center" label="agent/gclid" prop="gclid" sortable="custom">
            <template slot-scope="scope">
              {{ scope.row.gclid }}<br>
              {{ scope.row.user_agent }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="日期" prop="date_add" width="180">
            <template slot-scope="scope">
              {{ scope.row.date_add }}<br>
              {{ scope.row.log_date }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="250">
            <template slot-scope="scope">
              <el-button size="mini" type="success" @click="handleSync(scope.row)">同步</el-button>
              <el-button size="mini" type="warning" @click="handleAction('edit', scope.row)">编辑</el-button>
              <el-button size="mini" type="danger" @click="handleAction('delete', scope.row)">删除</el-button>
            </template>
          </el-table-column>

        </el-table>

        <el-pagination
          v-if="data.length"
          background
          class="mt-pagination"
          :current-page="page"
          :page-sizes="[10,20,50,100]"
          :page-size="pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
        <el-dialog
          append-to-body
          :title="title"
          :width="width"
          :visible.sync="innerDialogVisible"
          :close-on-click-modal="false"
        >
          <el-form :model="temp" label-position="left" label-width="120px">
            <el-form-item v-if="action !== 'delete'" label="id_cart">
              <el-input v-model="temp.id_cart" />
            </el-form-item>
            <el-form-item v-if="action !== 'delete'" label="id_product">
              <el-input v-model="temp.id_product" />
            </el-form-item>
            <el-form-item v-if="action !== 'delete'" label="id_order">
              <el-input v-model="temp.id_order" />
            </el-form-item>
            <el-form-item v-if="action !== 'delete'" label="gclid">
              <el-input v-model="temp.gclid" />
            </el-form-item>
          </el-form>

          <span slot="footer" class="dialog-footer">
            <el-button @click="innerDialogVisible = false">取 消</el-button>
            <el-button :type="action !== 'delete'?'primary':'danger'" @click="confirm">确 定</el-button>
          </span>
        </el-dialog>
      </el-main>

    </el-container>
    <googleconversionfile :visible="googleConversionFileVisual" @closeDialog="googleConversionFileVisual=false" />
    <sendmail
      :dialog-visible="sendMailVisible"
      :emailbox_id="emailbox_id"
      :mail_receiver="mail_receiver"
      :mail_to="mail_to"
      :pre_subject="pre_subject"
      :pre_body="pre_body"
      @close="handleCloseSendMail"
    />
  </div>
</template>

<script>
import { Get, Sync, Put, Delete } from '@/api/orders/shopping_cart'
import { Get as GetWebsite } from '@/api/erp/elicink/website'
import qs from 'qs'
import Googleconversionfile from './element/googleconversionfile'
import Sendmail from '../email/element/sendmail'
import Single_website_select from '../erp/elicink/elements/single_website_select'

const orderMapper = {
  'ascending': 0,
  'descending': 1,
  'null': ''
}
export default {
  components: { Single_website_select, Sendmail, Googleconversionfile },
  data() {
    return {
      sendMailVisible: false,
      mail_to: '',
      mail_receiver: '',
      emailbox_id: '',
      pre_subject: '',
      pre_body: '',
      googleConversionFileVisual: false,
      select_web: '',
      select_type: 'registe_not_pay',
      websites: [],
      data: [],
      title: 'shopping cart 信息',
      listLoading: false,
      kwInput: '',
      order_by: 'date_add',
      order_desc: 1,
      // pagination
      pagesize: 20,
      page: 1,
      total: 0,

      action: null,
      dialogVisible: false,
      temp: {
        gclid: '',
        id_cart: '',
        id_product: '',
        id_order: '',
        id: ''
      },
      width: '',
      innerDialogVisible: false
    }
  },
  created() {
    // this.handleGetWebsite()
    this.getList()
  },
  methods: {
    handleReplayEmail(row) {
      this.pre_subject = row.firstname + ' ' + row.lastname + ' your order has 10% off now!(only today)'
      this.pre_body = '<p>Hi,' + row.firstname + ' ' + row.lastname + '</p><p>You have place an order of</p><p><a href="' + row.product_url + '">' + row.product_name + '</a></p><p>But you did not finish the payment, is there anything we can do for you?</p><p>We give you a <strong><span style="color: #ff0000;">10% off</span></strong> code here: <strong>OFF10TODAY</strong></p>'
      this.pre_body += '<p>&nbsp;</p><p>&nbsp;</p><p>Best Wish from ' + row.website__domain + '</p>'
      this.mail_to = row.email
      this.mail_receiver = row.sender_email
      this.sendMailVisible = true
    },
    handleCloseSendMail(arg) {
      this.sendMailVisible = false
    },
    handleGetWebsite() {
      GetWebsite().then(response => {
        this.websites = response.data.data
      })
    },
    resetTemp() {
      this.temp = {
        gclid: '',
        id_cart: '',
        id_product: '',
        id_order: '',
        id: ''
      }
    },
    getList() {
      this.listLoading = true
      Get(null, qs.stringify({
        kw: this.kwInput,
        website_id: this.select_web,
        pagesize: this.pagesize,
        select_type: this.select_type,
        page: this.page,
        order_by: this.order_by,
        order_desc: this.order_desc
      }))
        .then(response => {
          this.scrollTop()
          this.data = response.data.data
          this.listLoading = false
          this.total = response.data.total
        }).catch(err => {
          console.log(err)
          this.listLoading = false
        })
    },
    handleSync(row) {
      if (row.id === '') {
        this.notify('id为空')
        return
      }
      this.listLoading = true
      Sync({
        id: row.id
      }
      ).then(response => {
        this.notify('处理成功')
        this.listLoading = false
      }).catch(err => {
        console.log(err)
        this.listLoading = false
      })
    },
    handleAction(action, row) {
      this.action = action
      switch (action) {
        case 'delete':
          this.width = '30%'
          this.title = `确认要删除${row.ad}?`
          this.temp = Object.assign({}, row)
          this.innerDialogVisible = true
          break
        case 'edit':
          this.width = '50%'
          this.title = `修改${row.ad} ${row.domain}`
          this.temp = Object.assign({}, row)
          this.innerDialogVisible = true
          break
        case 'add':
          this.width = '50%'
          this.title = `增加`
          this.innerDialogVisible = true
          break
      }
    },
    confirm() {
      const _data = this.temp
      switch (this.action) {
        // case 'add':
        //   this.listLoading = true
        //   Post({
        //     gclid: _data.gclid,
        //     id: _data.id
        //   }
        //   ).then(response => {
        //     this.innerDialogVisible = false
        //     this.getList()
        //     this.$emit('reload')
        //     this.notify('添加成功')
        //     this.listLoading = false
        //   }).catch(err => {
        //     console.log(err)
        //     this.listLoading = false
        //   })
        //   break
        case 'delete' :
          this.listLoading = true
          Delete(_data.id).then((response) => {
            this.innerDialogVisible = false
            this.getList()
            this.$emit('reload')
            this.notify('删除成功')
          }).catch(err => {
            console.log(err)
            this.listLoading = false
          })
          break
        case 'edit':
          this.listLoading = true
          Put(_data.id, {
            gclid: _data.gclid,
            id: _data.id
          }).then((response) => {
            this.innerDialogVisible = false
            this.getList()
            this.notify('更新成功')
          }).catch(err => {
            console.log(err)
            this.listLoading = false
          })
          break
      }
    },
    notify(message, duration) {
      this.$notify({
        title: '成功',
        message: message,
        type: 'success',
        duration: duration || 2000
      })
    },
    // pageSize 改变后触发 table 更新
    handleSizeChange(val) {
      this.pagesize = val
      this.getList()
    },
    // page 改变后触发 table 更新
    handlePageChange(val) {
      this.page = val
      this.getList()
    },
    // 点击搜索
    handleSearch() {
      this.page = 1
      this.getList()
    },
    handleSort(v) {
      this.order_by = v.prop
      this.order_desc = orderMapper[v.order]
      this.getList()
    },
    scrollTop() {
      window.scrollTo(0, 0)
    },
    close() {
      this.$emit('closeMyDialog', false)
    }
  }
}
</script>

<style scoped>
  .app-container >>> table, tr {
    border-color: black;
  }

  .el-header {
    height: 120px;
    margin-top: 10px;
  }

  .el-header, .el-footer {
    color: white;
  }

  .el-container >>> .pointer {
    cursor: pointer;
    color: #409EFF;
  }

  .el-container >>> a:visited {
    color: purple;
  }

  .el-container >>> a:link {
    color: #409EFF;
  }

  .el-container >>> a:active {
    color: red;
  }

  .app-container >>> a:hover {
    color: red;
    text-decoration: underline;
  }
</style>
